//
//  UIDevice+HKExtension.swift
//  App架构Swift
//
//  Created by 胡锦涛 on 2019/2/19.
//  Copyright © 2019 胡锦涛. All rights reserved.
//

import UIKit

extension UIDevice{
    
    func blankof<T>(type:T.Type) -> T {
        let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size)
        let val = ptr.pointee
        ptr.deinitialize(count: 1)
        return val
    }
    
    /// 磁盘总大小
    var hk_TotalDiskSize:Int64{
        var fs = blankof(type: statfs.self)
        if statfs("/var",&fs) >= 0{
            return Int64(UInt64(fs.f_bsize) * fs.f_blocks)
        }
        return -1
    }
    
    /// 磁盘可用大小
    var hk_AvailableDiskSize:Int64{
        var fs = blankof(type: statfs.self)
        if statfs("/var",&fs) >= 0{
            return Int64(UInt64(fs.f_bsize) * fs.f_bavail)
        }
        return -1
    }
    
    /// 将大小转换成字符串用以显示
    func hk_fileSizeToString(fileSize:Int64) -> String{
        
        let fileSize1 = CGFloat(fileSize)
        
        let KB:CGFloat = 1024
        let MB:CGFloat = KB*KB
        let GB:CGFloat = MB*KB
        
        //return String(format: "%.1f GB", CGFloat(fileSize1)/GB)
        
        if fileSize < 10
        {
            return "0 B"
        }else if fileSize1 < KB
        {
            return "< 1 KB"
        }else if fileSize1 < MB
        {
            return String(format: "%.1f KB", CGFloat(fileSize1)/KB)
        }else if fileSize1 < GB
        {
            return String(format: "%.1f MB", CGFloat(fileSize1)/MB)
        }else
        {
            return String(format: "%.1f GB", CGFloat(fileSize1)/GB)
        }
    }
}
